<!--
 * @Author: zhangjingyu
 * @Date: 2021-04-19 10:04:28
 * @LastEditors: zhangjingyu
 * @LastEditTime: 2021-05-06 09:58:27
 * @FilePath: \vprisk10.14\src\views\componentsTest\userTest.vue
 * @Description: 试验封装table 规格(以用户管理为例)
-->
<template>
  <div>
    <vp-grid
      url="/api-sys/sys/user/queryUserForPage"
      :searchForm="searchForm"
      :saveForm = "saveForm"
      @afterClearSearch="after"
      ref="grid"
      @saveFunc = "saveFunc"
      :addOrEdit.sync="addOrEdit"
      :saveFlg.sync="saveFlg"
    >
      <div slot="search" title="搜索条件">
        <el-form
          :model="searchForm"
          ref="searchForm"
          label-width="90px"
          label-position="left"
          size="mini"
        >
          <el-form-item label="姓　　名：">
            <el-input
              v-model.trim="searchForm.realName"
              style="width: 150px"
            ></el-input>
          </el-form-item>
          <el-form-item label="用 户 名：" prop="userName">
            <el-input
              v-model.trim="searchForm.userName"
              style="width: 150px"
            ></el-input>
          </el-form-item>
          <el-form-item label="所属机构：" prop="orgId">
            <el-cascader
              clearable
              filterable
              :options="orgList"
              v-model="searchForm.orgId"
              :props="{
                checkStrictly: true,
                emitPath: false,
                value: 'orgId',
                label: 'orgName'
              }"
              :show-all-levels="false"
              style="width: 150px"
              ref="searchOrgTree"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="状　　态：" prop="useFlag">
            <el-select
              v-model="searchForm.useFlag"
              placeholder="请选择"
              style="width: 150px"
            >
              <el-option label="启用" value="1"></el-option>
              <el-option label="锁定" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="角　　色：" prop="roleName">
            <el-input
              v-model="searchForm.roleName"
              style="width: 150px"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
       <div slot="button" title="按钮区">
        <vp-toolbar type="add" text="新增" url="/api-sys/sys/user/save" :beforeAction="abc" dialogTitle="用户管理新增" @action="addFunc" />
        <vp-toolbar type="edit" text="编辑" url="/api-sys/sys/user/save" dialogTitle="用户管理编辑" @action ='editFucnc' />
        <vp-toolbar type="delete" text="锁定" url="/api-sys/sys/user/lockUser" dialogTitle="用户锁定" useInterFunc idField='userId'/>
        <vp-toolbar type="delete" text="解锁" url="/api-sys/sys/user/unlockUser" dialogTitle="用户解锁" useInterFunc idField='userId'/>
        <vp-toolbar type="delete" text="注销" url="/api-sys/sys/user/cancelUsing" dialogTitle="用户注销" useInterFunc idField='userId'/>
        <vp-toolbar ref="roleCheck" type="checkTable" text="角色授权表格数据选择" @action="roleBtn" :tableData="tableDataRole" :tableProps="[{prop:'roleCode',label:'角色编号'},{prop:'roleName',label:'角色名称'}]" dialogTitle="角色授权" useInnerTable @check="roleCheck"/>
        <vp-toolbar ref="projetCheck" type="checkTree" text="工程授权表格数据选择" :treeData="tableDataRole" :treeProps="{value:'roleCode',label:'roleName'}" node-key="roleCode" dialogTitle="工程授权" useInnerTree @check="roleCheck"/>
      </div>
      <div slot="col" title="列表">
        <vp-col width="55" type="selection" fixed="left" />
        <vp-col prop="userName" label="用户名" />
        <vp-col prop="realName" label="用户姓名" sortable ></vp-col>
        <vp-col prop="org.orgName" label="机构" sortable ></vp-col>
        <vp-col prop="useFlag" label="状态" dictFormate="sys_userFlg"></vp-col>
        <vp-col prop="roles" label="授权角色" sortable diyFormat :diyFormater="row => row.roles.map(v => v.roleName).toString()"
        ></vp-col>
      </div>
      <div slot="dialogBody" title="新增编辑弹窗表单">
           <el-form
        :model="saveForm"
        ref="saveForm"
        label-width="97px"
        label-position="left"
        :rules="saveFormRules"
      >
            <el-form-item label="用户名：" prop="userName">
              <el-input
                v-model.trim="saveForm.userName"
                maxlength="40"
              ></el-input>
            </el-form-item>
            <el-form-item label="用户姓名：" prop="realName">
              <el-input
                v-model.trim="saveForm.realName"
                maxlength="50"
              ></el-input>
            </el-form-item>
            <el-form-item label="用户密码：" prop="password">
              <el-input
                v-model.trim="saveForm.password"
                type="password"
                maxlength="40"
                @blur="passwordChange"
              ></el-input>
            </el-form-item>
            <el-form-item label="确认密码：" prop="passwordStr">
              <el-input
                v-model.trim="saveForm.passwordStr"
                type="password"
                maxlength="40"
                @blur="passwordChange"
              ></el-input>
            </el-form-item>
            <el-form-item label="所属机构：" prop="orgId">
           
                <el-cascader
                  clearable
                  filterable
                  :options="orgList"
                  v-model="saveForm.orgId"
                  :props="{
                    checkStrictly: true,
                    emitPath: false,
                    expendTrigger: 'hover',
                    value: 'orgId',
                    label: 'orgName'
                  }"
                  :show-all-levels="false"
                  ref="saveOrgTree"
                  style="width: 100%"
                ></el-cascader>
            </el-form-item>
            <el-form-item label="用户状态：" prop="useFlag">
              <el-select
                v-model="saveForm.useFlag"
                disabled
                style="width: 100%"
              >
                <el-option value="1" label="启用"></el-option>
                <el-option value="0" label="撤销"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="员工编号：" prop="empNo">
              <el-input v-model.trim="saveForm.empNo" maxlength="40"></el-input>
            </el-form-item>
            <el-form-item label="身份证号：" prop="idcard">
              <el-input
                v-model.trim="saveForm.idcard"
                maxlength="40"
              ></el-input>
            </el-form-item>
            <el-form-item label="办公电话：" prop="officePhone">
              <el-input
                v-model.trim="saveForm.officePhone"
                maxlength="40"
              ></el-input>
            </el-form-item>
            <el-form-item label="移动电话：" prop="mobilePhone">
              <el-input
                v-model.trim="saveForm.mobilePhone"
                maxlength="40"
              ></el-input>
            </el-form-item>
            <el-form-item label="家庭电话：" prop="famliyPhone">
              <el-input
                v-model.trim="saveForm.famliyPhone"
                maxlength="40"
              ></el-input>
            </el-form-item>
            <el-form-item label="邮箱地址：" prop="email">
              <el-input v-model.trim="saveForm.email" maxlength="40"></el-input>
            </el-form-item>
      </el-form>
      </div>
    </vp-grid>
  </div>
</template>

<script>
import vpGrid from "@/components/vprisk-grid/VpriskGrid";
import vpToolbar from "@/components/vprisk-grid/VpToolbar";
import vpCol from "@/components/vprisk-grid/VpCol";
import { systemManage } from "@/api/index";
// import {nodeApi}  from "@/api/nodeServer/userImg";
import sm4 from "@/lib/gmsm4/index";
export default {
  components: { vpGrid, vpToolbar, vpCol },
  data() {
    return {
      searchForm: {},
      orgList:[],
      addOrEdit:false,
      saveFlg:1,
      key: "40ca11f573cce61cc28e19998d5bb1c8",
      saveForm:{},
      tableDataRole:[],
            saveFormRules: {
        userName: [
          {
            required: true,
            message: "该输入项为必输项",
            trigger: "blur"
          },
          {
            pattern: /^[0-9a-zA-Z_]{3,16}$/,
            message: "只能输入3-16位的英文字母、数字、下划线",
            trigger: "blur"
          },
          { validator: this.userNameValid, trigger: "blur" }
        ],
        realName: [
          {
            required: true,
            message: "该输入项为必输项",
            trigger: "blur"
          }
        ],
        password: [
          {
            required: true,
            message: "该输入项为必输项",
            trigger: "blur"
          },
          { validator: this.validFirtPassword, trigger: "blur" }
        ],
        passwordStr: [
          {
            required: true,
            message: "该输入项为必输项",
            trigger: "blur"
          },
          { validator: this.validPassword, trigger: "blur" }
        ],
        orgId: [
          {
            required: true,
            message: "该输入项为必输项",
            trigger: "blur"
          }
        ],
        status: [
          {
            required: true,
            message: "该输入项为必输项",
            trigger: "blur"
          }
        ],
        empNo: [
          {
            pattern: /^[0-9a-zA-Z_]{0,50}$/,
            message: "只能输入0-50位的英文字母、数字、下划线",
            trigger: "blur"
          }
        ],
        idcard: [
          {
            pattern: /^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
            message: "请输入有效的身份证号码",
            trigger: "blur"
          }
        ],
        officePhone: [
          {
            pattern: /^0\d{2,3}-[1-9]\d{6,7}$/,
            message: "请按正确格式输入电话号码（区号-电话号码）",
            trigger: "blur"
          }
        ],
        famliyPhone: [
          {
            pattern: /^0\d{2,3}-[1-9]\d{6,7}$/,
            message: "请按正确格式输入电话号码（区号-电话号码）",
            trigger: "blur"
          }
        ],
        mobilePhone: [
          {
            pattern: /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/,
            message: "请按正确格式输入手机号",
            trigger: "blur"
          }
        ]
      },
    };
  },
  created(){
    this.getOrgList();
    this.queryAllRole();
    console.log('路由',this.$router)
  },
  methods: {
       // 查询角色列表
    queryAllRole() {
      systemManage.queryRoles().then(res => {
        if (res.code == 200) {
          this.tableDataRole = res.datas;
        }
      });
    },
    abc(v){
       if(this.$refs.grid.selection.length<1){
        return false
      }
    },
      // 获取机构数据
    getOrgList() {
      systemManage.getOrganTree().then(res => {
        console.log(res, "机构");
        this.orgList = res;
      });
    },
     // 编辑时如果密码被更改，使用密码策略
    passwordChange() {
      if (this.saveFlg == 2 && this.saveFlg != "password") {
        this.getPasswordRlue({
          operateType: "2",
          userId: this.saveForm.userId
        });
      }
    },
    after() {
      console.log("清除搜索条件后");
    },
      // 密码策略获取
    getPasswordRlue(data) {
      systemManage.passwardValidRule(data).then(res => {
        let list = res.data.rules;
        // 前n次旧密码
        if (this.saveFlg != 1) {
          this.hisPwd = res.data.str_not_his_numbs.rule;
        }
        let passwordRule = [
          {
            required: true,
            message: "该输入项为必输项",
            trigger: "blur"
          },
          { validator: this.validFirtPassword, trigger: "blur" }
        ];
        for (let i = 0; i < list.length; i++) {
          let obj = {
            pattern: eval("/" + list[i].rule + "/"),
            message: list[i].msg,
            trigger: "blur"
          };
          passwordRule.push(obj);
        }
        this.saveFormRules.password = passwordRule;
      });
    },
      // 两个密码校验
    validPassword(rule, value, callback) {
      if (this.saveForm.password === this.saveForm.passwordStr) {
        callback();
      } else {
        callback(new Error("两次输入密码不一致"));
      }
    },
    // 用户名是否重复校验
    userNameValid(rule, value, callback) {
      // 只在新增时校验
      if (this.saveFlg != 1) {
        callback();
        return;
      }
      systemManage.userNameValid({ userName: value }).then(res => {
        if (res.code == 200) {
          callback();
        } else {
          callback(new Error(res.message || "用户名已存在"));
        }
      });
    },
     addFunc() {
      this.saveFlg = 1;
      // 新增使用密码策略
      this.getPasswordRlue({ operateType: "1" });

      for (let k in this.saveForm) {
        this.saveForm[k] = "";
      }
      this.saveForm.useFlag = "1";
      this.addOrEdit = true;
      this.$nextTick(() => {
        // 清除校验结果
        this.$refs.saveForm.clearValidate();
      });
    },
    editFucnc(val){
         this.saveFlg = 2;
      // 编辑默认不使用密码策略，若修改密码会触发密码策略校验
      this.saveFormRules.password = [
        {
          required: true,
          message: "该输入项为必输项",
          trigger: "blur"
        }
      ];
      let selection = this.$refs.grid.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据进行修改");
      }
      let row = selection[0];
      let form = { ...row };
      this.saveForm.userId = form.userId;
      this.saveForm.userName = form.userName;
      this.saveForm.realName = form.realName;
      this.saveForm.password = "password";
      this.saveForm.passwordStr = "password";
      this.saveForm.orgId = form.org.orgId;
      this.saveForm.orgName = form.org.orgName;
      this.saveForm.useFlag = form.useFlag;
      this.saveForm.empNo = form.empNo;
      this.saveForm.idcard = form.idcard;
      this.saveForm.officePhone = form.officePhone;
      this.saveForm.mobilePhone = form.mobilePhone;
      this.saveForm.famliyPhone = form.famliyPhone;
      this.saveForm.email = form.email;

      this.addOrEdit = true;
    },
    saveFunc() {
      this.$refs["saveForm"].validate(valid => {
        if (valid) {
          //加密
          let form = JSON.parse(JSON.stringify(this.saveForm));
          form.password =
            form.password == "password"
              ? "password"
              : sm4.encryptWithECB(this.key, this.saveForm.password);
          form.passwordStr =
            form.passwordStr == "password"
              ? "password"
              : sm4.encryptWithECB(this.key, this.saveForm.passwordStr);
          systemManage
            .saveUser(form)
            .then(res => {
              if (res.code == 200) {
                console.log(res);
                this.$message.success("保存成功");
                this.addOrEdit = false;
                this.$refs.grid.reload();
              } else {
                return this.$message.error(res.message);
              }
            })
            .catch(err => {});
        }
      });
    },
    roleBtn(e){
        console.log(e)
        // 点击逻辑 
    },
    porjectBtn(){
         
    },
    roleCheck(vm,selection){
        console.log(selection,el) 
        vm.dialogClose() //关闭窗口
    },
  }
};
</script>

<style lang="scss" scoped>
</style>
